<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: zhanglh
  Date: 2019/9/10/010
  Time: 19:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>上师文章管理</title>
    <link href="${pageContext.request.contextPath}/layui/css/layui.css" type="text/css" rel="stylesheet">
    <style>
        /*复选框位置居中*/
        .layui-table-cell .layui-form-checkbox[lay-skin="primary"] {
            top: 50%;
            transform: translateY(-50%);
        }
    </style>
    <script src="${pageContext.request.contextPath}/js/jquery-1.12.4.js"></script>
    <script type="application/javascript" src="${pageContext.request.contextPath}/layui/layui.js"></script>
</head>
<body>
<%--数据表--%>
<table id="all"></table>

<%--工具栏--%>
<div class="layui-btn-group" id="myToolbar" style="display: none">
    <button type="button" class="layui-btn layui-btn-sm" onclick="toAdd()">
        <i class="layui-icon">&#xe61f; 添加</i>
    </button>
    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="batchDeletion()">
        <i class="layui-icon">&#xe640; 批量删除</i>
    </button>
    <div class="layui-inline">
        <div class="layui-input-block layui-input-inline">
            <input type="text" id="key" placeholder="在此输入要查询的关键字" class="layui-input">
        </div>
        <div class="layui-input-inline">
            <button type="button" class="layui-btn layui-btn-primary" onclick="search()">
                <i class="layui-icon">&#xe615; 搜索</i>
            </button>
        </div>
    </div>
</div>

<%--表单--%>
<form class="layui-form" id="toForm" style="display: none" lay-filter="form">
    <br/>
    <div class="layui-form-item" hidden>
        <label class="layui-form-label">编号</label>
        <div class="layui-input-inline">
            <input type="text" id="articleId" name="articleId" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">标题</label>
        <div class="layui-input-inline">
            <input type="text" lay-verify="required" id="articleName" name="articleName" placeholder="请输入文章标题"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">上师</label>
        <div class="layui-input-inline">
            <select name="guruId" id="guruId" lay-verify="required">
                <option value="">请选择上师</option>

            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">封面</label>
        <div class="layui-input-inline">
            <div class="layui-upload-drag" id="articleImage">
                <i class="layui-icon"></i>
                <p>点击上传图片，或将图片拖拽到此处</p>
            </div>
        </div>
        <div class="layui-input-inline">
            <div class="layui-upload-list">
                <img class="layui-upload-img" src="" title="图片预览" alt="图片预览"
                     id="demo1" height="135px">
                <p id="demoText"></p></div>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">内容</label>
        <div class="layui-input-inline">
            <textarea name="articleContent" id="articleContent" lay-verify="required" placeholder="请输入文章内容"
                      class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="doSubmit" id="doSubmit">提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<script type="text/javascript">
    //渲染下拉框
    $.ajax({
        url: "${pageContext.request.contextPath}/guru/allGuru",
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                if (data[i].guruStatus) {
                    $("select[name='guruId']").append("<option value=" + data[i].guruId + " disabled>" + data[i].guruNickname + "(该账号已冻结)" + "</option>")
                } else {
                    $("select[name='guruId']").append("<option value=" + data[i].guruId + ">" + data[i].guruNickname + "</option>")
                }
            }
        }
    });

    var file_status = false;
    var doForm = "";
    // 表格信息
    layui.use(["table", "form", "upload"], function () {
        var table = layui.table;
        var form = layui.form;
        table.render({
            elem: "#all",
            url: "${pageContext.request.contextPath}/article/all",
            page: true,
            toolbar: "#myToolbar",
            size: "lg",
            cols: [[
                {type: "checkbox"},
                {title: "序号", type: "numbers"},
                // {title: "编号", field: "articleId", width: 60},
                {title: "标题", field: "articleName"},
                {title: "上师", field: "guruNickname"},
                {title: "封面", field: "articleImage", templet: "#img", width: 80},
                {title: "内容", field: "articleContent"},
                {title: "状态", field: "articleStatus", templet: "#state", width: 60},
                {title: "操作", templet: "#operating"}
            ]]
        });
        // 拦截添加操作
        form.on('submit(doSubmit)', function (data) {
            return false;
        });
    });
    var uploadInst;
    var files;
    //上传信息
    layui.use(["upload", "table", "layer"], function () {
        var table = layui.table;
        var layer = layui.layer;
        var upload = layui.upload;
        //拖拽上传
        uploadInst = upload.render({
            elem: '#articleImage',
            url: '${pageContext.request.contextPath}/article/' + doForm,
            data: {
                articleId: function () {
                    return $("#articleId").val();
                },
                articleName: function () {
                    return $("#articleName").val();
                },
                articleContent: function () {
                    return $("#articleContent").val();
                },
                guruId: function () {
                    return $("#guruId").val();
                }
            },
            accept: "images",
            acceptMime: 'image/*',
            // size: 500,
            auto: false,
            bindAction: "#doSubmit",
            choose: function (obj) {
                file_status = true;
                //将每次选择的文件追加到文件队列
                files = obj.pushFile();
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#demo1').attr('src', result); //图片链接（base64）
                });
            },
            error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            },
            done: function (res, index) {
                if (res) {
                    //关闭弹出层
                    layer.closeAll();
                    //刷新表格
                    table.reload("all");
                    //弹出提示信息
                    file_status = false;
                    layer.msg("操作成功");
                    delete files[index]; //删除文件队列已经上传成功的文件
                } else {
                    //弹出提示信息
                    layer.msg("操作失败");
                }
            }
        });
    });

    //无图片上传
    $('#doSubmit').click(function () {
        if (!file_status) {
            var articleId = $("#articleId").val();
            var articleName = $("#articleName").val();
            var articleContent = $("#articleContent").val();
            $.ajax({
                url: '${pageContext.request.contextPath}/article/' + doForm,
                type: "post",
                data: {
                    "articleId": articleId,
                    "articleName": articleName,
                    "articleContent": articleContent
                },
                success: function (data) {
                    layui.use(["layer", "table"], function () {
                        var table = layui.table;
                        var layer = layui.layer;
                        if (data) {
                            //关闭弹出层
                            layer.closeAll();
                            //刷新表格
                            table.reload("all");
                            //弹出信息
                            return layer.msg("操作成功");
                        } else {
                            return layer.msg("操作失败");
                        }
                    })
                }
            })
        } else {
            return false;
        }
    });

    // 搜索
    function search() {
        var key = $("#key").val();
        layui.use('table', function () {
            var table = layui.table;
            table.reload("all", {
                where: {"articleName": key}
            })
        })
    }

    // 添加弹出框
    function toAdd() {
        //清空数据
        document.getElementById("toForm").reset();
        $("#demo1").prop("src", "");
        //请求网址改为添加
        uploadInst.reload({
            url: "${pageContext.request.contextPath}/article/add"
        });
        doForm = "add";
        // 弹出输入框
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.open({
                type: 1,
                title: "添加上师",
                content: $("#toForm"),
                area: "520px",
                anim: 1,
                maxmin: true,
                cancel: function (index, layero) {
                    layer.msg("添加操作已取消");
                }
            })
        });
    }

    //修改弹出框
    function toUpdate(id) {
        layui.use(['layer', 'form'], function () {
            var layer = layui.layer;
            var form = layui.form;
            //刷新数据
            $.ajax({
                url: "${pageContext.request.contextPath}/article/selectOne",
                data: {"articleId": id},
                type: "post",
                success: function (data) {
                    form.val("form", {
                        "articleId": data.articleId,
                        "articleName": data.articleName,
                        "articleNickname": data.articleNickname
                    });
                    $("#demo1").prop("src", "${pageContext.request.contextPath}" + data.articleImage);
                    //请求更改为更新
                    uploadInst.reload({
                        url: "${pageContext.request.contextPath}/article/update"
                    });
                    doForm = "update";
                }
            });
            layer.open({
                type: 1,
                title: "修改上师信息",
                content: $("#toForm"),
                area: "530px",
                anim: 1,
                maxmin: true,
                cancel: function (index, layero) {
                    layer.msg("修改操作已取消");
                }
            })
        })
    }


    // 删除
    function toDelete(id) {
        layui.use(["layer", "table"], function () {
            var layer = layui.layer;
            var table = layui.table;
            layer.confirm('是否删除该上师，删除后不可恢复?', {icon: 3, title: '警告'}, function (index) {
                $.ajax({
                    url: "${pageContext.request.contextPath}/article/remove",
                    data: "ids=" + id,
                    type: "post",
                    success: function (data) {
                        if (data) {
                            // 关闭弹出框
                            layer.closeAll();
                            // 成功提示
                            layer.msg("删除成功");
                            // 刷新表格
                            table.reload("all");
                        } else {
                            layer.msg("删除失败，请重试");
                            layer.close(index);
                        }
                    }
                });
            }, function () {
                layer.msg("删除操作已取消");
            });
        })
    }

    //批量删除
    function batchDeletion() {
        layui.use(["layer", "table"], function () {
            var layer = layui.layer;
            var table = layui.table;
            // 获取到选择的数据
            var checkStatus = table.checkStatus("all");
            var length = checkStatus.data.length;
            //判断是否有数据
            if (length) {
                layer.confirm('是否删除所选文章?', {icon: 3, title: '警告'}, function (index) {
                        // 将id封装为新的数组
                        var ids = new Array(length);
                        for (var i = 0; i < length; i++) {
                            ids[i] = checkStatus.data[i].articleId;
                        }
                        // 发送删除请求
                        $.ajax({
                            url: "${pageContext.request.contextPath}/article/remove",
                            data: "ids=" + ids,
                            type: "post",
                            success: function (data) {
                                if (data) {
                                    // 成功提示
                                    layer.msg("删除成功");
                                    // 关闭弹出框
                                    layer.close(index);
                                    // 刷新表格
                                    table.reload("all");
                                } else {
                                    layer.msg("删除失败，请重试");
                                    layer.close(index);
                                }
                            }
                        });
                    },
                    function () {
                        layer.msg("删除操作已取消");
                    })
            } else {
                layer.msg("请先选择要删除的文章");
            }
        })
    }

    //下架
    function toFreeze(id, status) {
        layui.use(["layer", "table"], function () {
            var layer = layui.layer;
            var table = layui.table;
            layer.confirm('是否确认进行此操作?', {icon: 3, title: '警告'}, function (index) {
                $.ajax({
                    url: "${pageContext.request.contextPath}/article/freeze",
                    data: {"articleId": id, "articleStatus": status},
                    type: "post",
                    success: function (da) {
                        if (da) {
                            // 修改成功,弹出成功提示
                            layer.msg("操作成功");
                            //刷新表格
                            table.reload("all");
                        } else {
                            // 修改失败,弹出失败提示
                            layer.msg("操作失败，请重试");
                        }
                    }
                });
            }, function () {
                layer.msg("操作已取消");
            })
        })
    }

</script>
<script type="text/html" id="operating">
    {{# if(d.articleStatus==0){ }}
    <button type="button" class="layui-btn layui-btn-normal layui-btn-xs" onclick="toFreeze('{{ d.articleId }}',1)">
        <i class="layui-icon">&#xe6b1; 下架</i>
    </button>
    {{# }else{ }}
    <button type="button" class="layui-btn layui-btn-normal layui-btn-xs" onclick="toFreeze('{{ d.articleId }}',0)">
        <i class="layui-icon">&#xe674; 上架</i>
    </button>
    {{# } }}
    <button type="button" class="layui-btn layui-btn-xs" onclick="toUpdate('{{ d.articleId }}')">
        <i class="layui-icon">&#xe642; 修改</i>
    </button>
    <button type="button" class="layui-btn layui-btn-danger layui-btn-xs" onclick="toDelete('{{ d.articleId }}')">
        <i class="layui-icon">&#xe640; 删除</i>
    </button>
</script>
<script type="text/html" id="img">
    <img src="${pageContext.request.contextPath}{{d.articleImage}}" title="{{d.articleNickname}}" style="width: 50px">
</script>
<script type="text/html" id="state">
    {{# if(d.articleStatus==0){ }}
    正常
    {{# }else{ }}
    下架
    {{# } }}
</script>
</body>
</html>
